package com.yunzo.coc.api;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.upload.UploadFile;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.yunzo.coc.common.bean.Code;
import com.yunzo.coc.common.bean.FileResponse;
import com.yunzo.coc.common.utils.FileUtils;
import com.yunzo.coc.common.utils.IMGSize;
import com.yunzo.coc.common.utils.StringUtils;
import com.yunzo.coc.interceptor.TokenInterceptor;
import com.yunzo.coc.model.GroupMemberModel;

/**
 * 
 * 文件上传总的控制器，所有文件上传类表单均拆分成文件上传和文本提交
 * @author xiaobo
 */
public class FileAPIController extends BaseAPIController {
	/**
	 * 处理单文件或多文件上传，上传成功后，返回url集合
	 */
	public void upload(){
        if (!methodType("post")) {
            render404();
            return;
        }
        FileResponse response = new FileResponse();
        Map<String,Object> imgmap=null;
        String headimg=getPara("photoforandroidheadimage");
        if(headimg!=null)
        {
        	
        	try {
        		String mid=getPara("mid");
        		String groupid=getPara("groupid");
        		if(mid!=null)
        		{
					byte[] encode= Base64.decode(headimg);
					ByteArrayOutputStream btteout=new ByteArrayOutputStream();
					btteout.write(encode);
					btteout.flush();
					imgmap = FileUtils.saveUploadFile(btteout);
					GroupMemberModel nowUser = GroupMemberModel.dao.findFirst(MEMBERMIDSSQL,mid);
//					boolean flag = gminfo.set(GroupMemberinfoModel.HEADIMAGE, avatar).update();
					boolean flag = nowUser.set(GroupMemberModel.HEADIMAGE, imgmap.get("imgsrc").toString()).update();
					if(!flag)
					{
						response.setCode(Code.FAIL);
	        			 return;
					}
					response.setDatum(imgmap.get("imgsrc").toString());
        		}else
        		{
        			 response.setCode(Code.FAIL);
        			 return;
        		}
			} catch (Base64DecodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }else{
  
        String tempsize=null;
		try {
			List<UploadFile> fileList = getFiles();//已接收到的文件
			if(fileList != null && !fileList.isEmpty()){
			    Map<String, String> urls = new HashMap<String, String>();//用于保存上传成功的文件地址
				List<String> failedFiles = new ArrayList<String>(); //用于保存未成功上传的文件名
                
                for(UploadFile uploadFile : fileList){
					File file=uploadFile.getFile();
					if(uploadFile.getParameterName().equals("myheadimg"))
					{
						tempsize=IMGSize.X88.value();
					}else if(uploadFile.getParameterName().equals("showimg")){
						tempsize=IMGSize.X640.value();
					}else {
						tempsize=IMGSize.X650.value();
					}
					imgmap = FileUtils.saveUploadFile(file,tempsize);
                    if (!imgmap.get("msg").equals("100")) {
                        failedFiles.add(uploadFile.getParameterName());//标记为上传失败
                    } else {
                        //返回相对路径,用于响应
                        urls.put(uploadFile.getParameterName(), imgmap.get("imgsrc_slt").toString());
                    }
				}
			    response.setDatum(urls);
			    if (failedFiles.size() > 0) {
			        response.setCode(Code.FAIL);//表示此次上传有未上传成功的文件
			        response.setFailed(failedFiles);
			    }
			}else{
				response.setCode(Code.ARGUMENT_ERROR).setMessage("uploadFileName can not be null");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Code.ERROR);
		}
		}
        
		renderJson(response);
	}
}
